package com.sc.VenusQueryBeta.ui.fragments.account.daikuan;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.zhouwei.library.CustomPopWindow;
import com.hengjun.kingstar.sdk.base.BasePresenter;
import com.hengjun.kingstar.sdk.base.fragment.BaseMVPCompatFragment;
import com.hengjun.kingstar.sdk.utils.LogUtil;
import com.hengjun.kingstar.sdk.utils.LogUtils;
import com.hengjun.kingstar.sdk.utils.ResourcesUtils;
import com.hengjun.kingstar.sdk.utils.SpUtils;
import com.hengjun.kingstar.sdk.utils.ToastUtils;
import com.sc.VenusQueryBeta.R;
import com.sc.VenusQueryBeta.adapter.PopAdapter;
import com.sc.VenusQueryBeta.adapter.account.daikuan.DaiKuanAdapter01;
import com.sc.VenusQueryBeta.constant.Constants;
import com.sc.VenusQueryBeta.contract.account.daikuan.DaiKuan01Contract;
import com.sc.VenusQueryBeta.global.MyApplication;
import com.sc.VenusQueryBeta.model.bean.account.CurrencyListBean;
import com.sc.VenusQueryBeta.model.bean.account.daikuan.DaiKuanBean01;
import com.sc.VenusQueryBeta.model.bean.login.QueryRegisBean;
import com.sc.VenusQueryBeta.model.bean.login.UsersLoginBean;
import com.sc.VenusQueryBeta.presenter.account.daikuan.DaiKuan01Presenter;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.header.MaterialHeader;
import retrofit2.Call;

import static android.view.Gravity.CENTER;

public class DaiKuan01Fragment extends BaseMVPCompatFragment<DaiKuan01Contract.DaiKuanPresenter> implements DaiKuan01Contract.IDaiKuan01Activity, BaseQuickAdapter.RequestLoadMoreListener {


    private static DaiKuan01Fragment fragment;
    @BindView(R.id.ibtn_daikuan_back)
    ImageButton ibtnDaikuanBack;
    @BindView(R.id.rv_daikuan01)
    RecyclerView rvDaikuan01;
    @BindView(R.id.ptr_class)
    PtrClassicFrameLayout ptrClass;
    @BindView(R.id.tv_empty)
    TextView tvEmpty;
    @BindView(R.id.chooise_company)
    TextView chooiseCompany;
    @BindView(R.id.total_money)
    TextView totalMoney;
    @BindView(R.id.vp_fragment)
    FrameLayout vpFragment;
    private QueryRegisBean queryRegisBean;
    private int clientindex;
    private int roomid;
    private UsersLoginBean loginBean;
    private DaiKuanBean01 daiKuanBean01;
    private DaiKuanAdapter01 daiKuanAdapter01;
    private String roomname;
    private boolean isAllYear = false;
    private boolean isUpdate;
    private String currency;
    private CustomPopWindow mClubPopWindow;
    private RecyclerView clubrecyclerView;
    private PopAdapter popAdapter;
    private CurrencyListBean mallRoomListBean;

    public static DaiKuan01Fragment newInstance(QueryRegisBean queryRegisBean, int clientindex, int roomId, String currency) {
        Bundle args = new Bundle();
        args.putInt(Constants.CLIENTINDEX, clientindex);
        args.putInt(Constants.ROOMID, roomId);
        args.putString(Constants.CURRENCY_TYPE, currency);
        args.putSerializable(Constants.QUERY_SETTING, queryRegisBean);
        fragment = new DaiKuan01Fragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public boolean onBackPressedSupport() {
        pop();
        return true;
    }

    @NonNull
    @Override
    public BasePresenter initPresenter() {
        return DaiKuan01Presenter.newInstance();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_dai_kuan01_fragment;
    }

    @Override
    public void initUI(View view, @Nullable Bundle savedInstanceState) {
//        initHeadView();
        chooiseCompany.setText(currency);
        daiKuanAdapter01 = new DaiKuanAdapter01(R.layout.item_daikuan01);
        rvDaikuan01.setAdapter(daiKuanAdapter01);
        rvDaikuan01.setLayoutManager(new LinearLayoutManager(mContext));
        initClub();
        reFreshListener();//下拉刷新
        daiKuanAdapter01.setOnLoadMoreListener(this, rvDaikuan01);//加载更多
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        if (queryRegisBean != null && queryRegisBean.getServerSetting() != null && !queryRegisBean.getServerSetting().getServerAddress().equals("")) {
            showProgressDialog("請稍等...");
            mPresenter.queryAllCurrencyList(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().
                    getServerProject(), queryRegisBean.getServerSetting().getServerPort());
        }

    }

    @Override
    public void initData() {
        super.initData();
        if (fragment.getArguments() != null) {
            loginBean = SpUtils.getObject(MyApplication.app, UsersLoginBean.class);
            queryRegisBean = (QueryRegisBean) fragment.getArguments().getSerializable(Constants.QUERY_SETTING);
            clientindex = fragment.getArguments().getInt(Constants.CLIENTINDEX, 0);
            currency = fragment.getArguments().getString(Constants.CURRENCY_TYPE);
            roomid = fragment.getArguments().getInt(Constants.ROOMID, 0);
            LogUtils.e("123123========" + roomid);
        }
    }

//    /**
//     * 初始化头部
//     */
//    private void initHeadView() {
//        if (headView == null) {
//            headView = ResourcesUtils.inflate(R.layout.rv_top_cunka01);
//        }
//        if (footView == null) {
//            footView = ResourcesUtils.inflate(R.layout.rv_no_more_data);
//        }
//        if (errorView == null) {
//            errorView = ResourcesUtils.inflate(R.layout.view_network_error);
//        }
//        errorView.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                mPresenter.getDaiKuan01(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().
//                        getServerProject(), queryRegisBean.getServerSetting().getServerPort(), clientindex, loginBean.getId());
//            }
//        });
//        tv_jituan_money = headView.findViewById(R.id.tv_jituan_money);
//    }

    /**
     * 下拉刷新監聽
     */
    private void reFreshListener() {
        MaterialHeader header = new MaterialHeader(mActivity);
        ptrClass.addPtrUIHandler(header);
        ptrClass.setLastUpdateTimeRelateObject(this);//设置刷新支持时间
        ptrClass.setResistance(1.7f);//设置下拉的阻尼系数，值越大感觉越难下拉
        ptrClass.setDurationToCloseHeader(1000);//设置刷新完成，头部回弹时间，注意和前一个进行区别
        ptrClass.setPullToRefresh(false);//设置下拉过程中执行刷新，我们一般设置为false
        ptrClass.setKeepHeaderWhenRefresh(true);//设置刷新的时候是否保持头部
        ptrClass.setPtrHandler(new PtrDefaultHandler() {               //下拉刷新
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                //模拟联网，延迟更新数据
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (ptrClass != null && mPresenter != null) {
                            isUpdate = true;
                            mPresenter.getDaiKuan01(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().
                                    getServerProject(), queryRegisBean.getServerSetting().getServerPort(), clientindex, loginBean.getId(),chooiseCompany.getText().toString());
                        } else {
                            hideProgressDialog();
                        }
                        if (ptrClass != null) {
                            ptrClass.refreshComplete();//
                        } else {
                            hideProgressDialog();
                        }
                    }
                }, 1000);
            }
        });
    }

    @Override
    public void showDaikuanData1Success(final DaiKuanBean01 daiKuanBean01) {
        totalMoney.setText(daiKuanBean01.getLoannumSum());//設置總額
        if (daiKuanBean01.getList() != null&& daiKuanBean01.getList().size() > 0 ){
            ptrClass.setVisibility(View.VISIBLE);
            tvEmpty.setVisibility(View.GONE);
        }else {
            ptrClass.setVisibility(View.GONE);
            tvEmpty.setVisibility(View.VISIBLE);
        }
//        daiKuanAdapter01.removeAllFooterView();
        if (daiKuanAdapter01.getData().size() == 0) {
            initRecycleView(daiKuanBean01);
        } else {
            if (isUpdate) {
                isUpdate = false;
                if (daiKuanBean01.getList() != null && daiKuanBean01.getList().size() > 0) {
                    daiKuanAdapter01.setNewData(daiKuanBean01.getList());
                }
            } else {
                if (daiKuanBean01.getList() != null && daiKuanBean01.getList().size() > 0) {
                    daiKuanAdapter01.addData(daiKuanBean01.getList());
                }
            }
        }
        daiKuanAdapter01.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                LogUtil.e("Integer.parseInt(daiKuanBean01.getList().get(position).getRoomid() == null ? \"0\" : daiKuanBean01.getList().get(position).getRoomid())======="+Integer.parseInt(daiKuanBean01.getList().get(position).getRoomid() == null ? "0" : daiKuanBean01.getList().get(position).getRoomid()));
                start(DaiKuan02Fragment.newInstance(queryRegisBean, clientindex, Integer.parseInt(daiKuanBean01.getList().get(position).getRoomid() == null ? "0" : daiKuanBean01.getList().get(position).getRoomid()), daiKuanBean01.getList().get(position).getRoomname(),chooiseCompany.getText().toString()));

            }
        });
        hideProgressDialog();
        ptrClass.refreshComplete();//
    }

    @Override
    public void showNetworkError(Throwable throwable) {
//        daiKuanAdapter01.setEmptyView(errorView);
        hideProgressDialog();
    }

    @Override
    public void showLoadMoreError() {
        daiKuanAdapter01.loadMoreFail();
        hideProgressDialog();
    }

    @Override
    public void showqueryAllCurrencyList(final CurrencyListBean currencyListBean) {
        LogUtils.e("得到后台数据1======" + currencyListBean);
        if (currencyListBean != null && currencyListBean.getCurrencys() != null && currencyListBean.getCurrencys().size() > 0) {
//            roomId = Integer.parseInt(currencyListBean.getCurrencys().get(0).getCurrencys().get());
            //填充廳數據
            //初始化一个空list的adapter，网络错误时使用，第一次加载到数据时重新初始化adapter并绑定recycleview
            popAdapter = new PopAdapter(R.layout.pop_list_item, currencyListBean);
            clubrecyclerView.setAdapter(popAdapter);
            clubrecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
            //集團點擊監聽
            popAdapter.setOnCliCkItemListenerr(new PopAdapter.OnCliCkItemListener() {
                @Override
                public void clickItem(int position) {
                    isUpdate = true;
//                 roomId = Integer.parseInt(currencyListBean.getCurrencys().get(position).getRoomid());
                    chooiseCompany.setText(currencyListBean.getCurrencys().get(position).getCurrencyName1());//動態改變集團名稱
                    //查詢子戶口
                    showProgressDialog("正在加载");
//                    cunKaAdapter.removeAllHeaderView();
                    mPresenter.getDaiKuan01(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().
                            getServerProject(), queryRegisBean.getServerSetting().getServerPort(), clientindex, loginBean.getId(), chooiseCompany.getText().toString());

                    mClubPopWindow.dissmiss();
                }
            });
            //填充廳數據
            mallRoomListBean = currencyListBean;
//            //查询子户口
            if (queryRegisBean != null && !queryRegisBean.getServerSetting().getServerAddress().equals("")) {
                LogUtil.e("一开始没有调这里");
                isUpdate = true;
                mPresenter.getDaiKuan01(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().
                        getServerProject(), queryRegisBean.getServerSetting().getServerPort(), clientindex, loginBean.getId(), chooiseCompany.getText().toString());
            LogUtil.e("參數值========"+clientindex+loginBean.getId()+chooiseCompany.getText().toString());
            }
        }
    }

    @Override
    public void showNoMoreData() {
        daiKuanAdapter01.loadMoreEnd(true);
//        daiKuanAdapter01.setFooterView(footView);
        ToastUtils.showToast("已加载全部数据");
        hideProgressDialog();
    }

    /**
     * 填充數據
     *
     * @param daiKuanBean01
     */
    private void initRecycleView(final DaiKuanBean01 daiKuanBean01) {
        daiKuanAdapter01 = new DaiKuanAdapter01(R.layout.item_daikuan01, daiKuanBean01.getList());
//        daiKuanAdapter01.addHeaderView(headView);
        rvDaikuan01.setAdapter(daiKuanAdapter01);
    }

    @Override
    public void onLoadMoreRequested() {
        daiKuanAdapter01.loadMoreComplete();
//        //联网加载更多
//        ToastUtils.showToast("加载更多了");
        mPresenter.getMoreDaiKuan01(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().
                getServerProject(), queryRegisBean.getServerSetting().getServerPort(), clientindex, loginBean.getId(),chooiseCompany.getText().toString());
    }

    @OnClick({R.id.ibtn_daikuan_back, R.id.chooise_company})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ibtn_daikuan_back:
                pop();
                break;
            case R.id.chooise_company:
                chooiseCurrency();
                break;
        }
    }
    private void chooiseCurrency() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            mClubPopWindow.showAsDropDown(chooiseCompany, 0, 0, CENTER);
            // 设置背景颜色变暗
            WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
            lp.alpha = 0.5f;
            mActivity.getWindow().setAttributes(lp);
        } else {
            mClubPopWindow.showAsDropDown(chooiseCompany, 0, 0);
            // 设置背景颜色变暗
            WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
            lp.alpha = 0.5f;
            mActivity.getWindow().setAttributes(lp);
        }
    }
    /**
     * 选择集团小窗口
     */
    private void initClub() {
        View contentView = LayoutInflater.from(mActivity).inflate(R.layout.pop_list, null);
        //创建并显示popWindow
        mClubPopWindow = new CustomPopWindow.PopupWindowBuilder(mActivity)
                .setView(contentView)
                .setView(contentView).setOnDissmissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
                        lp.alpha = 1f;
                        mActivity.getWindow().setAttributes(lp);
                    }
                })
                .create();
        clubrecyclerView = contentView.findViewById(R.id.recyclerView);

    }
}
